import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-25
 * Time: 8:49
 */

/**
 *客户端
 * 1:从显示器上获得请求
 * 2:将请求发送给服务器
 * 3:从服务器获得响应
 * 4:将响应打印
 */
public class UdpEchoClient {
    DatagramSocket socket =null;
    private String serveIP;
    private int servePort;
    public UdpEchoClient(String serveIP,int servePort) throws SocketException {
        this.serveIP = serveIP;
        this.servePort = servePort;
        socket =new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        while(true){
            System.out.print("请输入你的请求:");
            Scanner scanner =new Scanner(System.in);
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serveIP),servePort);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient  udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
